package com.companyname.demo.cod.controller;

import com.companyname.demo.cod.domain.AjaxResult;
import com.companyname.demo.cod.domain.UserInfo;
import com.companyname.demo.cod.service.LoginService;
import com.companyname.demo.cod.util.RSAUtil;
import com.companyname.demo.cod.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestController
@Slf4j
@RequestMapping("/demo")
public class DemoController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getPublicKey")
    public AjaxResult getPublicKey() {
        Map<String, Object> publicKeyMap = RSAUtil.getPublicKeyMap();
        return AjaxResult.success(publicKeyMap);
    }

    @PostMapping("/registry")
    public AjaxResult registry() {
        String userName = RequestUtil.getParameter("userName");
        String password = RequestUtil.getParameter("password");
        log.info("收到请求参数：userName={},password={}", userName, password);
        try {
            return loginService.doRegistry(userName, password);
        } catch (IllegalArgumentException e1) {
            return AjaxResult.error(e1.getMessage());
        } catch (Exception e2) {
            return AjaxResult.error(e2.getMessage());
        }
    }

    @PostMapping("/login")
    public AjaxResult login(HttpServletResponse response) {
        String userName = RequestUtil.getParameter("userName");
        String password = RequestUtil.getParameter("password");
        try {
            return loginService.doLogin(userName, password, response);
        } catch (IllegalArgumentException e1) {
            return AjaxResult.error(e1.getMessage());
        } catch (Exception e2) {
            return AjaxResult.error(e2.getMessage());
        }
    }

    @GetMapping("/logout")
    public AjaxResult logout() {
        //1.从Request中获取UserInfo，根据userName从cookie中删除该用户的jwtsalt
        UserInfo userInfo = (UserInfo) RequestUtil.getRequest().getAttribute("userInfo");
        redisTemplate.opsForValue().getOperations().delete("jwtsalt:" + userInfo.getUserName());
        log.info("用户{}登出成功！", userInfo.getUserName());
        return AjaxResult.success("登出成功！");
    }


}
